package com.atguigu.tingshu.album.receiver;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.mapper.AlbumStatMapper;
import com.atguigu.tingshu.album.mapper.TrackStatMapper;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.rabbitmq.client.Channel;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
public class TrackReceiver {

    @Autowired
    private TrackInfoService trackInfoService;
    @Autowired
    private RedisTemplate redisTemplate;

    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_TRACK),
            value = @Queue(value = MqConst.QUEUE_TRACK_STAT_UPDATE, durable = "true",autoDelete = "false"),
            key = MqConst.ROUTING_TRACK_STAT_UPDATE
    ))
    public void trackStatUpdate(String trackStatMqVoJson, Message message, Channel channel){
        if (!StringUtils.isEmpty(trackStatMqVoJson)){
            //获取并解析消息对象
            TrackStatMqVo vo = JSON.parseObject(trackStatMqVoJson, TrackStatMqVo.class);
            //消息去重
            String key = "trackStatMsg:" + vo.getBusinessNo();
            Boolean result = redisTemplate.opsForValue().setIfAbsent(key, 1, 3, TimeUnit.MINUTES);
            if (result){
                try {
                    trackInfoService.updateStat(vo.getTrackId(),vo.getAlbumId(),vo.getStatType(),vo.getCount());
                } catch (Exception e) {
                    redisTemplate.delete(key);
                    e.printStackTrace();
                }
            }
            //手动确认
            try {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }



    }

}
